package com.group01.web.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;

import com.group01.config.AliPayConfig;
import com.group01.dto.Order.OrderPayDTO;
import com.group01.pojo.Order;
import com.group01.result.Result;
import com.group01.service.OrderService;
import com.group01.utils.LogUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
 * @Description 阿里支付宝支付Controller
 * @Author 翟玉龙
 * @Date 2024/6/26
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {
    /**
     * 注入
     */
    private final AliPayConfig aliPayConfig;
    private final OrderService orderService;

    public AliPayController(AliPayConfig aliPayConfig, OrderService orderService) {
        this.aliPayConfig = aliPayConfig;
        this.orderService = orderService;
    }

    @GetMapping("/pay")
    public void pay(OrderPayDTO order, HttpServletResponse httpResponse) throws Exception {
        //配置阿里支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), aliPayConfig.getFormat(), aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());

        //创建支付宝交易页面请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //设置支付成功后支付宝回调地址
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + order.getOrderId() + "\","
                + "\"total_amount\":\"" + order.getTotalPrice() + "\","
                + "\"subject\":\"" + order.getItemList() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //设置支付宝完成支付后跳转的本地页面
        request.setReturnUrl("http://localhost:8081/#/order");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            LogUtil.error("支付宝支付失败，失败原因：" , e);
        }
        httpResponse.setContentType("text/html;charset=" + aliPayConfig.getCharset());
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public Result<String> payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no").substring(params.get("trade_no").length() - 8);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单未已支付
                Order order = new Order();
                //设置订单ID
                order.setId(tradeNo);
                //设置订单状态
                order.setStatus(2);
                //设置支付编号
                order.setTrackingNumber(Integer.parseInt(alipayTradeNo));
                //设置支付方式
                order.setPayWay("支付宝沙箱环境支付");
                //设置支付时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                order.setPayDate(LocalDateTime.parse(gmtPayment, formatter));
                orderService.updateOrderById(order);
            }
        }
        return Result.success("支付成功", null);
    }
}